#include "nvs_settings.h"
#include "nvs_flash.h"

struct settings
{
    nvs_handle_t nvs_flash;
};

settings_t *nvs_settings_create(void)
{
    settings_t *settings = malloc(sizeof(settings_t));
    assert(settings);

    ESP_ERROR_CHECK(nvs_open("settings", NVS_READWRITE, &settings->nvs_flash));

    return settings;
}

char *nvs_settings_get_string(settings_t *settings, const char *key)
{
    // 查询需要获取的数据有多长
    size_t required_size = 0;
    int ret = nvs_get_str(settings->nvs_flash, key, NULL, &required_size);
    if (ret == ESP_ERR_NVS_NOT_FOUND)
    {
        return NULL;
    }
    ESP_ERROR_CHECK(ret);
    char *output = (char *)malloc(required_size);
    assert(output);
    ESP_ERROR_CHECK(nvs_get_str(settings->nvs_flash, key, output, &required_size));

    return output;
}

void nvs_settings_set_string(settings_t *settings, const char *key, const char *value)
{
    ESP_ERROR_CHECK(nvs_set_str(settings->nvs_flash, key, value));
    ESP_ERROR_CHECK(nvs_commit(settings->nvs_flash));
}

void nvs_settings_free(settings_t *settings)
{
    nvs_close(settings->nvs_flash);
    free(settings);
}
